package com.qianchang.microfinance.view.hsbindbank;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.ToastUtil;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.BindDataBean;
import com.qianchang.microfinance.bean.UserLoginInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.widgets.WebLayout;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultWebClient;

import org.json.JSONException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import butterknife.ButterKnife;


/**
 * 版 权: 广西鸿胜科技有限公司
 * 描 述: 绑定银行卡
 * 修 改 人: chen G L
 * 修改时间: 2018/1/10 16:33
 */

public class HSBindBankCardActivity extends BaseActivity{

//    @BindView(R.id.webView_id)
//    WebView webView;
//    @BindView(R.id.progressBarLoading)
//    ProgressBar mLoadingProgress;

    private LinearLayout mLinearLayout;
    protected AgentWeb mAgentWeb;
    private boolean isConfirmlGoing = false;    //从认证中心过来的？

    public boolean isConfirmlGoing() {
        return isConfirmlGoing;
    }

    public void setConfirmlGoing(boolean confirmlGoing) {
        isConfirmlGoing = confirmlGoing;
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bindbankcard_layout);
        ButterKnife.bind(this);
        initView();

        bindBankCard();

    }

    @Override
    protected void initView() {
        super.initView();
        setTitleName("绑定银行卡");

        Bundle bundle = getBundle();
        if(null != bundle)
        isConfirmlGoing = bundle.getBoolean("isConfirml",false);
        mLinearLayout = (LinearLayout) findViewById(R.id.mcontainer);


        mAgentWeb = AgentWeb.with(this)//
                .setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))//
                .useDefaultIndicator()//
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .setWebLayout(new WebLayout(this))
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
                .interceptUnkownScheme() //拦截找不到相关页面的Scheme
                .createAgentWeb()//
                .ready()
                .go(url);

        if(mAgentWeb!=null){
            //注入对象
            mAgentWeb.getJsInterfaceHolder().addJavaObject("android",new HSBindBankCardAndroidInterface(mAgentWeb,HSBindBankCardActivity.this));
        }


    }

    private void bindBankCard(){
        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();

        HttpParams params = new HttpParams();
        params.put("userId", usid);

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.BIND_BANKCARD, params, new RequestCallBack<BindDataBean>() {


            @Override
            public void onSuccess(JsonResult<BindDataBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    BindDataBean bindDataBean = response.getObject();
                    if(bindDataBean.getResult().equals("1")){
                        ToastUtil.getInstant().show(HSBindBankCardActivity.this, "银行卡已经绑定过了");
                        finish();
                    }else{
                        if(bindDataBean != null){
                            try {
                                pars = getParameter(bindDataBean);
                                initWebView();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }else{
                            ToastUtil.getInstant().show(HSBindBankCardActivity.this, response.getDescription());
                        }
                    }
                }else{
                    ToastUtil.getInstant().show(HSBindBankCardActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(HSBindBankCardActivity.this, msg);
                dismiss();
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });

    }

    private String getParameter(BindDataBean bindDataBean) throws JSONException, UnsupportedEncodingException {

        Map<String,String> map = new HashMap<String,String>();
        url = bindDataBean.getAction();
        String sign = bindDataBean.getSign();
        String platformNo = bindDataBean.getPlatformNo();
        String userDevice = bindDataBean.getUserDevice();
        String keySerial = bindDataBean.getKeySerial();
        String reqData = bindDataBean.getReqData();
        String serviceName = bindDataBean.getServiceName();

        map.put("sign",sign);
        map.put("platformNo",platformNo);
        map.put("userDevice",userDevice);
        map.put("keySerial",keySerial);
        map.put("reqData",reqData);
        map.put("serviceName",serviceName);
        String parameter = "";
        String subParameter = "";

        Iterator entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            parameter = parameter + key + "=" + URLEncoder.encode(value,"utf-8") + "&";
        }
        subParameter = parameter.substring(0, parameter.length() - 1);
        return subParameter;
    }




    private String url;
    private String pars = "";

    private void initWebView(){

//        WebSettings settings = webView.getSettings();
//        settings.setDefaultTextEncodingName("utf-8");       //设置网页默认编码
//        settings.setJavaScriptCanOpenWindowsAutomatically(true);
//        settings.setLoadWithOverviewMode(true);
//        //post请求(使用键值对形式，格式与get请求一样，key=value,多个用&连接)
////        urlParameter = "sign=" + URLEncoder.encode(sign,"utf-8") + "&" + "platformNo=" + URLEncoder.encode(platformNo,"utf-8") + "&" + "userDevice=" + URLEncoder.encode(userDevice,"utf-8") + "&" + "keySerial=" + URLEncoder.encode(keySerial,"utf-8") + "&" + "reqData=" + URLEncoder.encode(reqData,"utf-8") + "&" + "serviceName=" + URLEncoder.encode(serviceName,"utf-8");
//
////        webView.setWebViewClient(new MyWebViewClient());
////        webView.setWebChromeClient(new WebChromeClientProgress());       // 设置浏览器可弹窗
//        settings.setJavaScriptEnabled(true);                //支持javaScript
//        settings.setDomStorageEnabled(true);
//        webView.postUrl(url,pars.getBytes());



        mAgentWeb.getLoader().postUrl(url,pars.getBytes());

    }


    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            setTitle(title);
        }
    };

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.i("wmy", "BaseWebActivity onPageStarted = "+url);
        }

    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //mAgentWeb.destroy();
        mAgentWeb.getWebLifeCycle().onDestroy();
    }






//    // 监听
//    class MyWebViewClient extends WebViewClient {
//
//        @Override
//        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            return super.shouldOverrideUrlLoading(view, url);
//        }
//
//        @Override
//        public void onPageFinished(WebView view, String url) {
//            super.onPageFinished(view, url);
//        }
//
//        @Override
//        public void onPageStarted(WebView view, String url, Bitmap favicon) {
//            super.onPageStarted(view, url, favicon);
//        }
//
//        @Override
//        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
//            super.onReceivedError(view, errorCode, description, failingUrl);
//        }
//    }
//
//    private class WebChromeClientProgress extends WebChromeClient {
//        @Override
//        public void onProgressChanged(WebView view, int progress) {
//            if (mLoadingProgress != null) {
//                mLoadingProgress.setProgress(progress);
//                if (progress == 100) mLoadingProgress.setVisibility(View.GONE);
//            }
//            super.onProgressChanged(view, progress);
//        }
//
//        @Override
//        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//            return super.onJsAlert(view, url, message, result);
//        }
//
//        @Override
//        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
//            return super.onJsConfirm(view, url, message, result);
//        }
//
//        @Override
//        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
//            return super.onJsPrompt(view, url, message, defaultValue, result);
//        }
//    }
//
//
//    //改写物理按键——返回的逻辑
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        // TODO Auto-generated method stub
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (webView.canGoBack()) {
//                webView.goBack();//返回上一页面
//                return true;
//            }
//        }
//        return super.onKeyDown(keyCode, event);
//    }
//
//
//    @Override
//    protected void onDestroy() {
//        if (webView != null) {
//            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
//            webView.clearHistory();
////            ((WebView) webView.getParent()).removeView(webView);
//            webView.destroy();
//            webView = null;
//        }
//        super.onDestroy();
//    }

}
